package com.link.base.base.customerpricehistory.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.link.base.base.customerpricehistory.dao.mybatis.mapper.CustomerPriceHistoryMapper;
import com.link.base.base.customerpricehistory.model.CustomerPriceHistoryData;
import com.link.base.user.model.CoreUser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomerPriceHistoryDataListener extends AnalysisEventListener<CustomerPriceHistoryData> {

    private static final Logger logger = LogManager.getLogger(CustomerPriceHistoryDataListener.class);

    private CustomerPriceHistoryMapper customerPriceHistoryMapper;

    private CoreUser user;

    List<CustomerPriceHistoryData> list = new ArrayList<>();

    private int BATCH_COUNT = 100;

    private int middleBatchLen = 20;

    private int COUNT_NUM = 0;

    private StringBuilder errCountNum = new StringBuilder("");

    public CustomerPriceHistoryDataListener(CustomerPriceHistoryMapper customerPriceHistoryMapper, CoreUser user) {
        this.customerPriceHistoryMapper = customerPriceHistoryMapper;
        this.user = user;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        /*
        count 记录模板表头有几个，用以判断用户导入的表格是否和模板完全一致
        如果用户导入表格较模板的表头多，但其余符合模板，这样不影响则不需要
         */
        int count = 0;
        // 获取数据实体的字段列表
        Field[] fields = CustomerPriceHistoryData.class.getDeclaredFields();
        // 遍历字段进行判断
        /*for (Field field : fields) {
            // 获取当前字段上的ExcelProperty注解信息
            ExcelProperty fieldAnnotation = field.getAnnotation(ExcelProperty.class);
            // 判断当前字段上是否存在ExcelProperty注解
            if (fieldAnnotation != null) {
                ++count;
                // 存在ExcelProperty注解则根据注解的index索引到表头中获取对应的表头名
                String headName = headMap.get(fieldAnnotation.index());
                // 判断表头是否为空或是否和当前字段设置的表头名不相同
                if (StringUtils.isNull(headName) || !headName.equals(fieldAnnotation.value()[0])) {
                    // 如果为空或不相同，则抛出异常不再往下执行
                    throw new RuntimeException("模板错误，请检查导入模板");
                }
            }
        }*/
        // 判断用户导入表格的标题头是否完全符合模板
        /*if (count != headMap.size()) {
            throw new RuntimeException("模板错误，请检查导入模板");
        }*/
    }

    @Override
    public void invoke(CustomerPriceHistoryData customerPriceHistoryData, AnalysisContext analysisContext) {
        // 去掉头的行数
        Integer total = analysisContext.getTotalCount() - 1;
        if (total <= 0) {
            return;
        }
        // 初始化数据
        customerPriceHistoryData.setCreatedBy(user.getId());
        customerPriceHistoryData.setLastUpdatedBy(user.getId());
        customerPriceHistoryData.setCorpid(user.getCorpid());
        customerPriceHistoryData.setOrgId(user.getOrgId());
        customerPriceHistoryData.setPostnId(user.getPostnId());
        list.add(customerPriceHistoryData);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        try {
            this.saveData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("数据读取完成!");
    }

    /**
     * 保存
     * @throws Exception
     */
    private void saveData() throws Exception {
        if (null == list || list.size() == 0) {
            return;
        }
        // 计数器
        int count = 1;
        List<CustomerPriceHistoryData> toInsertPartsCostTempDataList = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        for (CustomerPriceHistoryData customerPriceHistoryData : list) {
            toInsertPartsCostTempDataList.add(customerPriceHistoryData);
            ids.add(customerPriceHistoryData.getId());
            if (count == BATCH_COUNT) {
                try {
                    customerPriceHistoryMapper.batchInserts(toInsertPartsCostTempDataList);
                } catch (Exception e) {
                    this.middleImport(toInsertPartsCostTempDataList);
                }
                count = 1;
                toInsertPartsCostTempDataList.clear();
                ids.clear();
            } else {
                count++;
            }
        }
        // 扫尾
        if (count > 0) {
            try {
                // 批量插入
                customerPriceHistoryMapper.batchInserts(toInsertPartsCostTempDataList);
            } catch (Exception e) {
                try {
                    this.middleImport(toInsertPartsCostTempDataList);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            // 重新计数
            count = 1;
            // 清空list，重新塞数据
            toInsertPartsCostTempDataList.clear();
            ids.clear();
        }
    }



    private void middleImport(List<CustomerPriceHistoryData> customerPriceHistoryDataList) throws Exception {
        // 计数器
        int count = 1;
        List<CustomerPriceHistoryData> toInsertZyAccountTempList = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        for (CustomerPriceHistoryData customerPriceHistoryData : customerPriceHistoryDataList) {
            toInsertZyAccountTempList.add(customerPriceHistoryData);
            ids.add(customerPriceHistoryData.getId());
            if (count == middleBatchLen) {
                customerPriceHistoryMapper.batchInserts(toInsertZyAccountTempList);
                count = 1;
                toInsertZyAccountTempList.clear();
                ids.clear();
            } else {
                count++;
            }
        }
        // 扫尾
        if (count > 0) {
            customerPriceHistoryMapper.batchInserts(toInsertZyAccountTempList);
            // 重新计数
            count = 1;
            // 清空list，重新塞数据
            toInsertZyAccountTempList.clear();
            ids.clear();
        }
    }

}
